import java.util.Random;

/**
 * 215. 数组中的第K个最大元素
 * https://leetcode.cn/problems/kth-largest-element-in-an-array/description/
 */
class Solution {
    public int findKthLargest(int[] nums, int k) {
        return qsort(nums, 0, nums.length - 1, k);
    }

    public int qsort(int[] nums, int l, int r, int k) {

        if(l == r) return nums[l];
        //1、随机选择一个基准元素
        int key = nums[new Random().nextInt(r - l + 1) + l];
        //2、根据基准元素，使数组分三块
        int left = l - 1, right = r + 1, i = l;
        while(i < right) {
            if(nums[i] < key) swap(nums, ++left, i++);
            else if(nums[i] == key) i++;
            else swap(nums, --right, i);
        }
        //3、分完三块，看第k大元素在哪个区间,分类讨论
        //[l, left], [left + 1, right - 1], [right, r]
        int a = left - l + 1, b = right - left - 1, c = r - right + 1;
        if(c >= k) return qsort(nums, right, r, k);
        else if(b + c >= k) return key;
        else return qsort(nums, l, left, k - b - c);
    }
    public void swap(int[] nums, int i, int j) {
        int tmp = nums[i];
        nums[i] = nums[j];
        nums[j] = tmp;
    }
}